// //顺序表
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;

typedef struct {
  ElemType *date;
  int length;
} SeqList;


// 顺序表 - 动态内存初始化
SeqList *intList() {
  SeqList *L = (SeqList *)malloc(sizeof(SeqList));
  L->date = (ElemType *)malloc(sizeof(ElemType) * MAXSIZE);
  L->length = 0;
  return L;
}

// 顺序表 - 添加元素
int addendElem(SeqList *L, ElemType e) {
  if (L->length >= MAXSIZE) {
    printf("顺序表已满");
    return 0;
  }
  L->date[L->length] = e;
  L->length++;
  return 1;
}

// 顺序表 - 插入元素
void insertElem(SeqList *L, int pos, ElemType e) {
  if (pos <= L->length) {
    for (int i = L->length - 1; i >= pos - 1; i--) {
      L->date[i + 1] = L->date[i];
    }
    L->date[pos - 1] = e;
    L->length++;
  }
}

// 顺序表 - 删除元素
int deleteElem(SeqList *L, int pos, ElemType *e) {
  *e = L->date[pos - 1];
  if (pos <= L->length) {
    for (int i = pos; i < L->length; i++) {
      L->date[i - 1] = L->date[i];
    }
  }
  L->length--;
  return 1;
}

// 顺序表 - 遍历
void listElem(SeqList *L) {
  for (int i = 0; i < L->length; i++) {
    printf("%d ", L->date[i]);
  }
  printf("\n");
}

// 顺序表 - 查找
int findElem(SeqList *L, ElemType e) {
  if (L->length <= 0) {
    printf("顺序表为空");
    return 0;
  }
  for (int i = 0; i < L->length; i++) {
    if (L->date[i] == e)
      return i + 1;
  }
  return 0;
}

int main(int argc, char const *argv[]) {
  SeqList *list = intList(list);
  addendElem(list, 4);
  addendElem(list, 17);
  addendElem(list, 45);
  printf("初始化完成,目前长度占用为%d\n", (*list).length);
  printf("目前占用内存%zu个字节\n", sizeof((*list).date));
  listElem(list);
  insertElem(list, 2, 5);
  listElem(list);
  ElemType delete;
  deleteElem(list, 2, &delete);
  printf("删除的数据为:%d\n", delete);
  listElem(list);
  printf("%d在顺序表的第%d个位置", 17, findElem(list, 17));
  free(list->date);
  free(list);
  return 0;
}